<template>
	<el-dialog
		:title="title"
		:visible.sync="dialogVisible"
		width="65%"
		top="6.5vh"
		:append-to-body="true"
		custom-class="user-edit"
	>
		<el-form
			ref="form"
			:model="form"
			:rules="rules"
			label-width="120px"
			label-suffix="："
			hide-required-asterisk
		>
			<el-form-item label="用户名" prop="username">
				<el-input
					v-model="form.username"
					@input="changeUsername"
					@blur="validateUsername"
					size="small"
				>
					<i
						v-if="usernameLoading"
						slot="suffix"
						class="el-input__icon el-icon-loading"></i>
				</el-input>
			</el-form-item>
			<el-form-item label="密码" prop="password">
				<el-input
					v-model="form.password"
					size="small"
					show-password
				></el-input>
			</el-form-item>
			<el-form-item label="性别" prop="gender">
				<el-select
					v-model="form.gender"
					size="small"
				>
					<el-option
						v-for="item in GENDER_LIST"
						:key="item.value"
						:label="item.label"
						:value="item.value">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="生日" prop="birthday">
				<el-date-picker
					v-model="form.birthday"
					type="date"
					size="small"
					value-format="yyyy-MM-dd"
				></el-date-picker>
			</el-form-item>
			<el-form-item label="邮箱" prop="email">
				<el-input
					v-model="form.email"
					size="small"
				></el-input>
			</el-form-item>
			<el-form-item label="手机号码" prop="phone">
				<el-input
					v-model="form.phone"
					size="small"
				></el-input>
			</el-form-item>
			<el-form-item prop="provinceCityArea" label="区域">
				<el-cascader
					v-model="form.provinceCityArea"
					style="width: 220px"
					size="small"
					filterable
					:options="options"
					:props="{ expandTrigger: 'hover' }"
				></el-cascader>
			</el-form-item>
			<el-form-item label="地址" prop="address">
				<el-input
					v-model="form.address"
					size="small"
				></el-input>
			</el-form-item>
			<el-form-item label="状态">
				<el-select
					v-model="form.isAvailable"
					size="small"
				>
					<el-option
						v-for="item in USER_STATUS_LIST"
						:key="item.value"
						:label="item.label"
						:value="item.value">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="角色">
				<el-select
					v-model="form.role"
					size="small"
				>
					<el-option
						v-for="item in ROLE_LIST"
						:key="item.value"
						:label="item.label"
						:value="item.value">
					</el-option>
				</el-select>
			</el-form-item>
		</el-form>
		<span slot="footer" class="dialog-footer">
	    <el-button
		    size="mini"
		    @click="dialogVisible = false">取 消</el-button>
	    <el-button
		    size="mini"
		    type="primary"
		    @click="saveUser">确 定</el-button>
	  </span>
	</el-dialog>
</template>

<script>
  import * as CONSTANT from '../../config/constant'
  import utils from "../../utils";
  import Validators from "../../config/validators";
  import options from "../../config/china-division";

  const validator = new Validators()
  export default {
    name: "edit",
    data() {
      return {
        ...CONSTANT,
        options: options,
        dialogVisible: false,
        user: null,
        rules: {
          username: [{required: true, validator: validator.validateUsername, trigger: 'change'}],
          password: [{required: true, validator: validator.validatePassword, trigger: 'change'}],
          gender: [{required: true, validator: validator.validateGender, trigger: 'change'}],
          birthday: [{required: true, validator: validator.validateBirthday, trigger: 'change'}],
          email: [{required: true, validator: validator.validateEmail, trigger: 'change'}],
          phone: [{required: true, validator: validator.validatePhone, trigger: 'change'}],
          address: [{required: true, validator: validator.validateAddress, trigger: 'change'}]
        },
        form: utils.getDefaultRegisterForm(),
        usernameLoading: false,
        loading: false,
        usernameError: undefined,
        passwordError: undefined,
        currentUsername: ''
      }
    },
    computed: {
      title() {
        if (!this.user) return '新增用户'
        return '编辑' + this.currentUsername
      }
    },
    watch: {
      'form.provinceCityArea': {
        deep: true,
        immediate: true,
        handler(list) {
          let [province, city, area] = list || []
          this.form.province = province || ''
          this.form.city = city || ''
          this.form.area = area || ''
        }
      },
      usernameError() {
        this.$refs.form.validateField('username')
      },
      passwordError() {
        this.$refs.form.validateField('password')
      }
    },
    mounted() {
      validator.context = this
      this.$bus.$on('user-edit', user => {
        let currentUsername = ''
        if (user === null) {
          this.form = utils.getDefaultRegisterForm()
        } else {
          this.user = user
          this.form = user
	        this.form.provinceCityArea = [user.province || '', user.city || '', user.area || '']
          currentUsername = user.username
        }
        this.currentUsername = currentUsername
        this.dialogVisible = true
      })
    },
    methods: {
      changeUsername() {
        this.usernameError = undefined
      },
      validateUsername() {
        const api = '/user/isUsernameValid'
        let username = this.form.username
        this.$cancel(api)
        this.usernameError = undefined
        if (!username) {
          this.usernameLoading = false
          return false
        }
        this.usernameLoading = true
        this.$axios.post(api, {
          username: this.form.username,
          uid: this.form.id
        }).then(({success, message}) => {
            if (!success) {
              this.usernameError = message
            }
          })
          .catch(thrown => {
            this.$message({
              type: 'error',
              message: thrown.message
            })
          })
          .finally(() => {
            this.usernameLoading = false
          })
      },
      saveUser() {
        this.$refs.form.validate(valid => {
          if (!valid) return false
          this.loading = true
          // let isUpdate = this.form.id > 0
	        let params = {
            ...this.form
	        }
          delete params.provinceCityArea
          this.$axios.post('/user/save', this.form)
            .then(({success, message}) => {
              if (success) {
                this.dialogVisible = false
                this.$bus.$emit('user-edit__success')
                this.$notify({
                  type: 'success',
                  title: '操作成功'
                })
              } else {
                if (/用户名/.test(message)) {
                  this.usernameError = message
                } else {
                  this.$message({
                    type: 'error',
                    message: message
                  })
                }
                this.$refs.form.validate()
              }
            })
            .catch(thrown => {
              this.$message({
                type: 'error',
                message: thrown.message
              })
            })
            .finally(() => {
              this.loading = false
            })
        })
      }
    }
  }
</script>

<style lang='less'>
	.user-edit {
		.el-dialog__body {
			text-align: center;
		}

		.el-form {
			width: 100%;
			max-width: 600px;
			margin: 0 auto;
		}

		.el-form-item__content {
			padding-right: 60px;
			text-align: left;

			& > * {
				width: 100%;
			}
		}
	}
</style>
